<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select v-model="q.cate_id" placeholder="请选择分类" size="small">
              <el-option :label="item.cate_name" :value="item.id" v-for="item in CateList" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px;">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="getArtList">筛选</el-button>
            <el-button type="info" size="small" @click="resetArtList">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button type="primary" size="small" class="btn-pub" @click="listVisible=true">发表文章</el-button>
      </div>

      <!-- 文章表格区域 -->
      <el-table :data="artList" style="width: 100%;" border stripe>
        <el-table-column label="文章标题" >
          <template v-slot='{row}'>
             <el-link type="primary" @click="showDetail(row.id)">{{row.title}}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="分类" prop="cate_name"></el-table-column>
        <el-table-column label="发表时间">
          <template v-slot='{row}'>{{getTime(row.pub_date)}}</template>
        </el-table-column>
        <el-table-column label="状态" prop="state"></el-table-column>
        <el-table-column label="操作">
          <template v-slot='{row}'><el-button type="danger" size="mini" @click="remove(row.id)">删除</el-button></template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="q.pagenum"
        :page-sizes="[2, 3, 5, 20]"
        :page-size="q.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
      <!-- 分页区域 -->
      <el-dialog
        :before-close='hClose'
        title="提示"
        :visible.sync="listVisible"
        fullscreen>
        <el-form :model="pubForm" :rules="rules" ref="pubForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="文章标题" prop="title">
            <el-input v-model="pubForm.title" placeholder="请输入文章标题"></el-input>
          </el-form-item>
          <el-form-item label="文章分类" prop="cate_id">
            <el-select v-model="pubForm.cate_id" placeholder="请选择活动区域" style="width: 100%;">
              <el-option :label="item.cate_name" :value="item.id" v-for="item in CateList" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="content">
             <!-- bidirectional data binding（双向数据绑定） -->
              <quill-editor v-model="pubForm.content" @blur="$refs.pubForm.validateField('content')">
              </quill-editor>
          </el-form-item>
          <el-form-item label="文章封面" prop="cover_img">
            <!-- 用来显示封面的图片 -->
            <img :src="pubIMG" alt="" class="cover-img" ref="imgRef" v-if="pubIMG"/>
            <img v-else src="../../../assets/images/cover.jpg" alt="" class="cover-img" ref="imgRef" />
            <br />
            <!-- 文件选择框，默认被隐藏 -->
            <input type="file" style="display: none;" accept="image/*" ref="iptFile" @change="changeAvatar"/>
            <!-- 选择封面的按钮 -->
            <el-button type="text" @click="$refs.iptFile.click()">+ 选择封面</el-button>
          </el-form-item>
          <el-button type="primary" @click="pubArticle('已发布')">发布</el-button>
          <el-button type="info" @click="pubArticle('草稿')">存为草稿</el-button>
        </el-form>
      </el-dialog>
      <el-dialog title="文章预览" :visible.sync="detailVisible" width="80%">
        <h1 class="title">{{ artDetail.title }}</h1>

        <div class="info">
          <span>作者：{{ artDetail.nickname || artDetail.username }}</span>
          <span>发布时间：{{ getTime(artDetail.pub_date) }}</span>
          <span>所属分类：{{ artDetail.cate_name }}</span>
          <span>状态：{{ artDetail.state }}</span>
        </div>

        <!-- 分割线 -->
        <el-divider></el-divider>

        <img :src="'http://www.liulongbin.top:3008' + artDetail.cover_img" alt="" />

        <div v-html="artDetail.content"></div>
</el-dialog>
    </el-card>
  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import dayjs from 'dayjs'

import { quillEditor } from 'vue-quill-editor'
export default {
  name: 'ArtList',
  components: {
    quillEditor
  },
  data () {
    return {
      detailVisible: false,
      artDetail: {},
      // 查询参数对象
      q: {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      },
      artList: [],
      total: 0,
      listVisible: false,
      rules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 1, max: 30, message: '文章标题的长度为1-30个字符', trigger: 'blur' }
        ],
        cate_id: [{ required: true, message: '请选择文章标题', trigger: 'change' }],
        content: [{ required: true, message: '请选择文章标题', trigger: 'blur' }],
        cover_img: [{ required: true, message: '请选择文章标题', trigger: 'change' }]
      },
      pubForm: {
        title: '',
        cate_id: '',
        content: '',
        cover_img: '',
        state: ''
      },
      pubIMG: '',
      CateList: []
    }
  },
  methods: {
    hClose () {
      this.$confirm('此操作将导致文件永久丢失, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.$refs.pubForm.resetFields()
        this.listVisible = false
      }).catch(() => {
      })
    },
    async getList () {
      const { data: res } = await this.$axios.get('/my/cate/list')
      if (res.code === 0) { this.CateList = res.data }
    },
    changeAvatar (e) {
      // console.log(e)
      const file = e.target.files[0]
      if (file) {
        this.pubForm.cover_img = file
        const fn = new FileReader()
        fn.readAsDataURL(file)
        fn.onload = (e) => { this.pubIMG = e.target.result }
      } else {
        this.pubForm.cover_img = ''
        this.pubIMG = ''
      }
      this.$refs.pubForm.validateField('cover_img')
    },
    pubArticle (data) {
      this.pubForm.state = data
      this.$refs.pubForm.validate(async valid => {
        if (!valid) return
        const fn = new FormData()
        Object.keys(this.pubForm).forEach(item => fn.append(item, this.pubForm[item]))
        const { data: res } = await this.$axios.post('/my/article/add', fn)
        // console.log(res)
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)
        this.$refs.pubForm.resetFields()
        this.listVisible = false
      })
    },
    async getArtList () {
      const { data: res } = await this.$axios.get('/my/article/list', { params: this.q })
      if (res.code === 0) {
        this.artList = res.data
        this.total = res.total
      }
    },
    getTime (date) {
      return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
      // console.log(date)
    },
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      this.q.pagesize = val
      this.getArtList()
    },
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      this.q.pagenum = val
      this.getArtList()
    },
    resetArtList () {
      this.q.cate_id = ''
      this.q.state = ''
      this.getArtList()
    },
    async remove (id) {
      // console.log(id)
      const { data: res } = await this.$axios.delete('/my/article/info', { params: { id } })
      if (res.code !== 0) return this.$message.error(res.message)
      this.$message.success(res.message)
      if (this.artList.length === 1 && this.q.pagenum > 1) {
        this.q.pagenum--
      }
      this.getArtList()
    },
    async showDetail (id) {
      // 请求详情数据
      const { data: res } = await this.$axios.get('/my/article/info', { params: { id } })
      if (res.code !== 0) return this.$message.error('获取文章详情失败!')
      this.artDetail = res.data
      // 展示对话框
      this.detailVisible = true
    }
  },
  created () {
    this.getList()
    this.getArtList()
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}
/deep/ .ql-editor{
  height: 300px;
}
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}
</style>
